<template>
  <div v-if="modelValue" class="modal-overlay" @click="handleOverlayClick">
    <div class="apple-card modal-dialog" @click.stop>
      <div class="apple-card__header">
        <h2 class="text-heading">重置密码</h2>
        <button 
          class="close-button apple-button apple-button--text"
          @click="handleClose"
        >
          ✕
        </button>
      </div>

      <div class="apple-card__body">
        <div class="user-info">
          <div class="user-avatar">
            <img 
              v-if="user?.avatar_url" 
              :src="user.avatar_url" 
              :alt="user.real_name"
              class="avatar-image"
            >
            <div v-else class="avatar-placeholder">
              {{ user?.real_name?.charAt(0)?.toUpperCase() || '?' }}
            </div>
          </div>
          <div class="user-details">
            <h3 class="user-name">{{ user?.real_name }}</h3>
            <p class="user-username">@{{ user?.username }}</p>
            <p class="user-email">{{ user?.email }}</p>
          </div>
        </div>

        <div class="warning-notice">
          <div class="warning-icon">⚠️</div>
          <div class="warning-content">
            <h4 class="text-body">安全提醒</h4>
            <p class="text-caption">
              重置密码后，用户当前的所有登录会话将被强制注销，需要使用新密码重新登录。
            </p>
          </div>
        </div>

        <form @submit.prevent="handleSubmit">
          <div class="form-group">
            <label class="form-label">新密码 *</label>
            <div class="password-input-wrapper">
              <input
                v-model="form.new_password"
                :type="showPassword ? 'text' : 'password'"
                class="apple-input"
                :class="{ 'apple-input--error': errors.new_password }"
                placeholder="请输入新密码"
                minlength="6"
                required
              >
              <button
                type="button"
                class="password-toggle"
                @click="showPassword = !showPassword"
              >
                {{ showPassword ? '👁️' : '🙈' }}
              </button>
            </div>
            <div v-if="errors.new_password" class="error-message">{{ errors.new_password }}</div>
            <div class="form-help">密码长度至少6位，建议包含字母、数字和特殊字符</div>
          </div>

          <div class="form-group">
            <label class="form-label">确认新密码 *</label>
            <div class="password-input-wrapper">
              <input
                v-model="form.confirm_password"
                :type="showConfirmPassword ? 'text' : 'password'"
                class="apple-input"
                :class="{ 'apple-input--error': errors.confirm_password }"
                placeholder="请再次输入新密码"
                required
              >
              <button
                type="button"
                class="password-toggle"
                @click="showConfirmPassword = !showConfirmPassword"
              >
                {{ showConfirmPassword ? '👁️' : '🙈' }}
              </button>
            </div>
            <div v-if="errors.confirm_password" class="error-message">{{ errors.confirm_password }}</div>
          </div>

          <div class="form-group">
            <label class="switch-label">
              <div class="switch-info">
                <span class="form-label">发送邮件通知</span>
                <span class="form-help">向用户邮箱发送密码重置通知</span>
              </div>
              <div 
                class="apple-switch"
                :class="{ 'apple-switch--active': form.send_email }"
                @click="form.send_email = !form.send_email"
              ></div>
            </label>
          </div>

          <!-- 密码强度指示器 -->
          <div v-if="form.new_password" class="password-strength">
            <div class="strength-label">密码强度：</div>
            <div class="strength-bar">
              <div 
                class="strength-fill"
                :class="getStrengthClass()"
                :style="{ width: getStrengthPercentage() + '%' }"
              ></div>
            </div>
            <div class="strength-text">{{ getStrengthText() }}</div>
          </div>
        </form>
      </div>

      <div class="apple-card__footer">
        <button 
          type="button"
          class="apple-button apple-button--secondary"
          @click="handleClose"
        >
          取消
        </button>
        <button 
          type="submit"
          class="apple-button apple-button--danger"
          :disabled="!isFormValid || submitting"
          @click="handleSubmit"
        >
          {{ submitting ? '重置中...' : '重置密码' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userApi } from '@/api/users'
import type { User } from '@/types/rbac'

// Props
interface Props {
  modelValue: boolean
  user: User | null
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'reset'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 表单数据
const form = ref({
  new_password: '',
  confirm_password: '',
  send_email: true
})

// 表单验证错误
const errors = ref({
  new_password: '',
  confirm_password: ''
})

// 状态
const submitting = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)

// 计算属性
const isFormValid = computed(() => {
  return form.value.new_password.trim() && 
         form.value.confirm_password.trim() && 
         !errors.value.new_password && 
         !errors.value.confirm_password
})

// 密码强度计算
const passwordStrength = computed(() => {
  const password = form.value.new_password
  if (!password) return 0
  
  let score = 0
  
  // 长度检查
  if (password.length >= 6) score += 1
  if (password.length >= 8) score += 1
  if (password.length >= 12) score += 1
  
  // 复杂度检查
  if (/[a-z]/.test(password)) score += 1
  if (/[A-Z]/.test(password)) score += 1
  if (/[0-9]/.test(password)) score += 1
  if (/[^A-Za-z0-9]/.test(password)) score += 1
  
  return Math.min(score, 5)
})

// 验证函数
const validatePassword = () => {
  const password = form.value.new_password
  if (!password) {
    errors.value.new_password = '新密码不能为空'
  } else if (password.length < 6) {
    errors.value.new_password = '密码至少6个字符'
  } else if (password.length > 128) {
    errors.value.new_password = '密码不能超过128个字符'
  } else {
    errors.value.new_password = ''
  }
  
  // 同时验证确认密码
  validateConfirmPassword()
}

const validateConfirmPassword = () => {
  const password = form.value.new_password
  const confirmPassword = form.value.confirm_password
  
  if (!confirmPassword) {
    errors.value.confirm_password = '请确认新密码'
  } else if (password !== confirmPassword) {
    errors.value.confirm_password = '两次输入的密码不一致'
  } else {
    errors.value.confirm_password = ''
  }
}

// 密码强度相关函数
const getStrengthPercentage = () => {
  return (passwordStrength.value / 5) * 100
}

const getStrengthClass = () => {
  const strength = passwordStrength.value
  if (strength <= 1) return 'strength-weak'
  if (strength <= 2) return 'strength-fair'
  if (strength <= 3) return 'strength-good'
  if (strength <= 4) return 'strength-strong'
  return 'strength-excellent'
}

const getStrengthText = () => {
  const strength = passwordStrength.value
  if (strength <= 1) return '弱'
  if (strength <= 2) return '一般'
  if (strength <= 3) return '良好'
  if (strength <= 4) return '强'
  return '极强'
}

// 重置表单
const resetForm = () => {
  form.value = {
    new_password: '',
    confirm_password: '',
    send_email: true
  }
  
  errors.value = {
    new_password: '',
    confirm_password: ''
  }
  
  showPassword.value = false
  showConfirmPassword.value = false
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}

// 点击遮罩关闭
const handleOverlayClick = () => {
  handleClose()
}

// 提交表单
const handleSubmit = async () => {
  if (!props.user) return
  
  validatePassword()
  validateConfirmPassword()
  
  if (!isFormValid.value) {
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要重置用户"${props.user.real_name}"的密码吗？重置后用户需要使用新密码重新登录。`,
      '确认重置密码',
      {
        confirmButtonText: '确定重置',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'apple-button--danger'
      }
    )
    
    submitting.value = true
    
    const response = await userApi.resetUserPassword(props.user.id, {
      new_password: form.value.new_password,
      send_email: form.value.send_email
    })
    
    if (response.success) {
      emit('reset')
      handleClose()
      
      if (form.value.send_email) {
        ElMessage.success('密码重置成功，已发送邮件通知用户')
      } else {
        ElMessage.success('密码重置成功')
      }
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
      ElMessage.error('重置密码失败')
    }
  } finally {
    submitting.value = false
  }
}

// 监听表单变化
watch(() => form.value.new_password, validatePassword)
watch(() => form.value.confirm_password, validateConfirmPassword)

// 监听对话框打开
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    resetForm()
  }
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: var(--spacing-lg);
}

.modal-dialog {
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  animation: modalSlideIn var(--duration-normal) var(--ease-out);
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.apple-card__header {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.close-button {
  position: absolute;
  right: 0;
  padding: var(--spacing-xs);
  font-size: 18px;
  opacity: 0.6;
}

.close-button:hover {
  opacity: 1;
}

.user-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  padding: var(--spacing-md);
  background-color: var(--bg-secondary);
  border-radius: var(--radius-medium);
}

.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background-color: var(--color-primary);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 600;
}

.user-details {
  flex: 1;
  min-width: 0;
}

.user-name {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.user-username {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: 12px;
  color: var(--text-secondary);
  font-family: 'SF Mono', Monaco, monospace;
}

.user-email {
  margin: 0;
  font-size: 12px;
  color: var(--text-tertiary);
}

.warning-notice {
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-sm);
  padding: var(--spacing-md);
  background-color: rgba(255, 149, 0, 0.1);
  border-left: 4px solid var(--color-warning);
  border-radius: var(--radius-medium);
  margin-bottom: var(--spacing-lg);
}

.warning-icon {
  font-size: 20px;
  margin-top: 2px;
}

.warning-content h4 {
  margin: 0 0 var(--spacing-xs) 0;
  color: var(--color-warning);
}

.warning-content p {
  margin: 0;
}

.form-group {
  margin-bottom: var(--spacing-lg);
}

.form-label {
  display: block;
  margin-bottom: var(--spacing-xs);
  font-weight: 500;
  color: var(--text-primary);
}

.form-help {
  margin-top: var(--spacing-xs);
  font-size: 12px;
  color: var(--text-tertiary);
}

.error-message {
  margin-top: var(--spacing-xs);
  font-size: 12px;
  color: var(--color-danger);
}

.password-input-wrapper {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: var(--spacing-sm);
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  padding: var(--spacing-xs);
  opacity: 0.6;
}

.password-toggle:hover {
  opacity: 1;
}

.switch-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  padding: var(--spacing-sm) 0;
}

.switch-info {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.switch-info .form-label {
  margin-bottom: 0;
}

.password-strength {
  margin-top: var(--spacing-md);
  padding: var(--spacing-md);
  background-color: var(--bg-secondary);
  border-radius: var(--radius-medium);
}

.strength-label {
  font-size: 12px;
  color: var(--text-secondary);
  margin-bottom: var(--spacing-xs);
}

.strength-bar {
  height: 4px;
  background-color: var(--bg-tertiary);
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: var(--spacing-xs);
}

.strength-fill {
  height: 100%;
  transition: all var(--duration-normal) var(--ease-out);
  border-radius: 2px;
}

.strength-weak {
  background-color: var(--color-danger);
}

.strength-fair {
  background-color: var(--color-warning);
}

.strength-good {
  background-color: var(--apple-blue);
}

.strength-strong {
  background-color: var(--color-success);
}

.strength-excellent {
  background-color: var(--apple-green);
}

.strength-text {
  font-size: 11px;
  color: var(--text-tertiary);
  text-align: right;
}

.apple-card__footer {
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .modal-overlay {
    padding: var(--spacing-md);
  }
  
  .modal-dialog {
    max-height: 95vh;
  }
  
  .apple-card__footer {
    flex-direction: column-reverse;
    gap: var(--spacing-sm);
  }
  
  .apple-card__footer .apple-button {
    width: 100%;
  }
}
</style>